package com.bw.module_home.viewmodel

import androidx.lifecycle.viewModelScope
import com.bw.lib_mvicore.model.BaseModel
import com.bw.lib_net.entity.ResponseEntity
import com.bw.module_home.intent.SimpleTypeIntent
import com.bw.module_home.model.entity.SimpleTypeEntity
import com.bw.module_home.model.service.VideoTypeService
import com.bw.module_home.state.SimpleTypeState
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

/**
 * @Author : ZhouZiYao
 * @Time : On 2023/11/22 14:10
 * @Description :
 */
class SimpleTypeViewModel: BaseModel<SimpleTypeIntent>() {

    private val service: VideoTypeService by lazy {
        VideoTypeService()
    }

    //可变
    private var _state: MutableStateFlow<SimpleTypeState> = MutableStateFlow<SimpleTypeState>(SimpleTypeState.Init)

    //不可变
    val state: StateFlow<SimpleTypeState> = _state.asStateFlow()

    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect {
                when (it){
                    is SimpleTypeIntent.GetSimpleType -> doSimpleType(it)
                }
            }
        }
    }

    private fun doSimpleType(it: SimpleTypeIntent.GetSimpleType) {
        viewModelScope.launch {
            flow<ResponseEntity<MutableList<SimpleTypeEntity>>> {
                val data = service.getSimpleType()
                emit(data)
            }.catch {e ->
                _state.value = SimpleTypeState.Failed(e.message.toString())
            }.filter {
                it != null
            }.collect{
                if (it.code == 0){
                    _state.value = SimpleTypeState.Success(it.data)
                }else{
                    _state.value = SimpleTypeState.Failed(it.msg)
                }
            }
        }
    }

}